package com.csdj.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.csdj.server.pojo.*;
import com.csdj.server.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyq
 * @since 2022-12-12
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private INationService nationService; //名族

    @Autowired
    private IPoliticsStatusService politicsStatusService; //政治面貌

    @Autowired
    private IJoblevelService joblevelService;  //职称

    @Autowired
    private IPositionService positionService; //职位

    @Autowired
    private IDepartmentService departmentService; //部门

    @ApiOperation(value = "员工信息分页查询")
    @GetMapping("/")
    public RespPageBean getEmployeeByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                          @RequestParam(defaultValue = "10") Integer size,
                                          Employee employee,
                                          LocalDate[] beginDateScope){
        return employeeService.getEmployeeByPage(currentPage,
                size,employee,beginDateScope);
    }

    @ApiOperation(value = "添加员工信息")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){

        return employeeService.insertEmp(employee);
    }

    @ApiOperation(value = "修改员工信息")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if(employeeService.updateById(employee)){
            return RespBean.success("修改成功!");
        }
        return RespBean.error("修改失败!");
    }

    @ApiOperation(value = "删除员工信息")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable("id") Integer id){
        if(employeeService.removeById(id)){
            return RespBean.success("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

    @ApiOperation(value = "获取所有的名族")
    @GetMapping("/nations")
    public List<Nation> getAllNation(){

        return nationService.list();
    }

    @ApiOperation(value = "获取所有的政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation(value = "获取所有的职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJobLevel(){

        return joblevelService.list();
    }

    @ApiOperation(value = "获取所有的职位")
    @GetMapping("/positions")
    public List<Position> getAllPosition(){
        return positionService.list();
    }

    @ApiOperation(value = "获取所有的部门")
    @GetMapping("/departments")
    public List<Department> getAllDepartment(){
        return departmentService.getAllDepartments();
    }


    @ApiOperation(value = "获取最大工号")
    @GetMapping("/maxWorkId")
    public RespBean getMaxWorkId(){

        return employeeService.maxWorkId();
    }

    @ApiOperation(value = "员工信息输入导出")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportExcel(HttpServletResponse response){

        //1.首先 获取员工信息数据
        List<Employee> list = employeeService.getAllEmployee(null);
        //2.创建 导出所需的参数
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
        //利用工具类 导出数据
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        //拿到输出流
        ServletOutputStream out=null;

        try {
            response.setHeader("content-type","application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls","UTF-8"));
            out=response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out!=null){
                try {
                    out.flush(); //刷新 缓存
                    out.close(); //关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @ApiOperation(value = "员工信息导入")
    @PostMapping("/import")
    public RespBean importExcel(MultipartFile file){
        ImportParams importParams=new ImportParams();
        //去掉标题行
        importParams.setTitleRows(1);
        //名族的 集合
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Position> positionList = positionService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Department> departmentList = departmentService.list();
        try {
            //导入 操作
            List<Employee> empList = ExcelImportUtil.importExcel(file.getInputStream(),
                    Employee.class, importParams);

            empList.forEach(employee->{
                //根据民族实体类的name 获取到对应的id
                //名族

                employee.setNationId(nationList.get(
                        nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌
                employee.setPoliticId(politicsStatusList.get(
                        politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());

                //职位
                employee.setPosId(positionList.get(
                        positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
               //职称
                employee.setJobLevelId(joblevelList.get(
                        joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //部门
                employee.setDepartmentId(departmentList.get(
                        departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
            });
            if(employeeService.saveBatch(empList)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RespBean.error("导入失败!");

    }


}
